package org.bbx.autoops.utils;


import cn.hutool.core.date.DateUtil;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.GlobalCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.bss.v2.region.BssRegion;
import com.huaweicloud.sdk.bss.v2.*;
import com.huaweicloud.sdk.bss.v2.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.bbx.autoops.utils.ParamPackage.xyChart;


@Slf4j
@Component
public class CostAnalysedUtil {

    @Value("${hw.ak}")
    private String ak;

    @Value("${hw.sk}")
    private String sk;


    /**
     * 月度陈本分析
     *
     * @param beginTime     开始时间
     * @param endTime       结束时间
     * @param timeMeasureId 时间单位。 1：天    2：月
     */
    public ListCostsResponse listCost(String beginTime, String endTime, Integer timeMeasureId) {
        ListCostsResponse response = null;

        ICredential auth = new GlobalCredentials()
                .withAk(ak)
                .withSk(sk);

        BssClient client = BssClient.newBuilder()
                .withCredential(auth)
                .withRegion(BssRegion.valueOf("cn-north-1"))
                .build();
        ListCostsRequest request = new ListCostsRequest();
        ListCostsReq body = new ListCostsReq();
        List<GroupBy> listbodyGroupby = new ArrayList<>();
        listbodyGroupby.add(
                new GroupBy()
                        .withType("dimension")
                        .withKey("ASSOCIATED_ACCOUNT")
        );
        TimeCondition timeConditionbody = new TimeCondition();
        timeConditionbody.withTimeMeasureId(timeMeasureId)
                .withBeginTime(beginTime)
                .withEndTime(endTime);
        body.withAmountType("NET_AMOUNT");
        body.withCostType("ORIGINAL_COST");
        body.withGroupby(listbodyGroupby);
        body.withTimeCondition(timeConditionbody);
        request.withBody(body);
        try {
            response = client.listCosts(request);
        } catch (ConnectionException e) {
            log.error(e.getMessage());
        }
        return response;

    }


    public Map<String, String> getXYChartDataMap(String id,String beginTime, String endTime ) {

        ListCostsResponse listCost = listCost(beginTime, endTime, 1);

        HashMap<String, String> m = new HashMap<>();
        if (listCost == null) {
            return m;
        }

        StringBuilder valueBuilder = new StringBuilder();
        StringBuilder keyBuilder = new StringBuilder();
        CostDataByDimension costData = listCost.getCostData().get(0);
        List<Cost> costs = costData.getCosts();
        String amountByCosts = costData.getAmountByCosts();
        Double maxXYChaxis = 0.0;
        if (!costs.isEmpty()) {
            for (int i = 0; i < costs.size(); i++) {
                Cost cost = costs.get(i);
                String v = cost.getAmount();
                valueBuilder.append(v);

                keyBuilder.append('"').append(DateUtil.parse(cost.getTimeDimensionValue()).toString("MM-dd")).append('"');

                if (i < costs.size() - 1) {
                    valueBuilder.append(",");
                    keyBuilder.append(",");
                }
                // 处理最大值
                maxXYChaxis = Math.max(maxXYChaxis, Double.parseDouble(v));
            }

            return xyChart(BigDecimal.valueOf(maxXYChaxis).multiply(BigDecimal.valueOf(1.2)).setScale(2, BigDecimal.ROUND_HALF_UP).toString(),
                    valueBuilder.toString(),
                    keyBuilder.toString(),
                    beginTime + "~" + endTime + "  成本分析   " + "(合计消费：" + amountByCosts +")", "元", id);

        }
        return m;
    }
}
